import { ref } from 'vue'
import { ElMessage } from 'element-plus'

export function useMediaFiles() {
  const mediaFiles = ref([])
  const loading = ref(false)
  const hasMore = ref(true)
  const currentPage = ref(1)
  const PAGE_SIZE = 50

  const loadMediaFiles = async (folderPath, reset = false) => {
    if (!folderPath || (loading.value && !reset) || (!hasMore.value && !reset)) return

    if (reset) {
      currentPage.value = 1
      mediaFiles.value = []
      hasMore.value = true
    }

    loading.value = true
    try {
      const result = await window.mediaManager.readMediaFiles(
        folderPath,
        currentPage.value,
        PAGE_SIZE
      )
      
      mediaFiles.value = reset ? result.files : [...mediaFiles.value, ...result.files]
      hasMore.value = result.hasMore
      currentPage.value++
    } catch (error) {
      console.error('Load media files failed:', error)
    } finally {
      loading.value = false
    }
  }

  const refreshFiles = (folderPath) => {
    loadMediaFiles(folderPath, true)
  }

  const clearThumbnailCache = async () => {
    if (loading.value) return
    
    try {
      loading.value = true
      await window.mediaManager.clearThumbnails()
      ElMessage.success('缓存清除成功')
      refreshFiles()
    } catch (error) {
      console.error('Clear cache failed:', error)
      ElMessage.error('缓存清除失败')
    } finally {
      loading.value = false
    }
  }

  return {
    mediaFiles,
    loading,
    hasMore,
    loadMediaFiles,
    refreshFiles,
    clearThumbnailCache
  }
} 